package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.MyException;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.itheima.common.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/3 16:53
 */

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<IPage<Dish>> page(int page, int pageSize, String name) {
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapprt = new LambdaQueryWrapper<>();
        queryWrapprt.like(StringUtils.hasLength(name), Dish::getName, name);
        queryWrapprt.orderByDesc(Dish::getSort);
        IPage<Dish> ipageResult = dishService.page(pageInfo, queryWrapprt);

        // 获取菜品分类，在category表中查询菜品分类
        // ipage中获取当前页数据
        List<Dish> records = ipageResult.getRecords();
        // 使用stream流封装dishdto返回给前端
        List<Dish> dishDtoList = records.stream().map((record) -> {
            Long categoryId = record.getCategoryId();
            // 根据dish表中的外键categoryid查询category表
            Category category = categoryService.getById(categoryId);
            // 获取category的菜品分类
            String categoryName = category.getName();
            // 创建dishDto将菜品分类封装进去
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            // 将dish里面的数据拷贝到dishDto中。
            BeanUtils.copyProperties(record, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
//        List<Dish> dishDtoList = new ArrayList<>();
//        for (Dish record : records) {
//            Long categoryId = record.getCategoryId();
//            Category category = categoryService.getById(categoryId);
//            // 查询出菜品对应的分类
//            String categoryName = category.getName();
//            // 将dish里面的属性赋值给DishDto为了给前端响应
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(record, dishDto);
//            dishDto.setCategoryName(categoryName);
//            dishDtoList.add(dishDto);
//        }
        ipageResult.setRecords(dishDtoList);
        return R.success(ipageResult);
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveDish(dishDto);
        // 增加新的菜品后，清空redis里面的缓存，重新加载
        String key = "dish_" + dishDto.getId() + "1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    @PostMapping("/status/{st}")
    public R status(@RequestParam int st, List<Long> ids) {
        return R.success("修改成功");
    }

    /**
     * 后台删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            if (dish.getStatus() == 1) {
                throw new MyException("起售状态无法删除");
            }
            dishService.removeById(id);
        }

        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> querryWrapper = new LambdaQueryWrapper<>();
            querryWrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(querryWrapper);
        }
        return R.success("删除成功");

    }

    /**
     * 1  c端用户菜品下的菜，dishDto。
     * 2  使用redis会减少并发情况下数据库访问的压力。
     * 所以在查询的时候先查询redis中是否有缓存，如果有就直接返回结果不继续查询数据库，
     * 如果redis中没有查询到缓存的信息就去查询数据库，然后将信息缓存到redis中，在下次访问的时候使用。
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getDishList(Dish dish) {
        List<DishDto> dishListDto;
        // 先构造动态的key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        // 从redis中获取
        dishListDto = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishListDto != null){
            return R.success(dishListDto);
        }

        LambdaQueryWrapper<Dish> querryWrapper = new LambdaQueryWrapper<>();
        querryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        querryWrapper.like(StringUtils.hasLength(dish.getName()), Dish::getName, dish.getName());
        List<Dish> dishList = dishService.list(querryWrapper);
        List<DishDto> dishDtoList = dishList.stream().map((dis) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dis, dishDto);
            // 查询关联的口味表
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, dis.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        // 将查询到的菜品存储到
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


}
